package com.itheima.tlias84.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias84.Util.JwtUtil;
import com.itheima.tlias84.Util.ResultUtil;
import com.itheima.tlias84.entity.Emp;
import com.itheima.tlias84.mapper.EmpMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 登录拦截 拦截器由spring提供
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
  @Resource
   EmpMapper empMapper;
    @Override
    public boolean preHandle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Object handler) throws IOException {
        log.info("开始执行http请求过滤");
//        //放行登录接口
//        String requestURI = servletRequest.getRequestURI();
//        if (requestURI.contains("login")) {
//           // chain.doFilter(servletRequest, servletResponse);
//            return true;
//        }

        //请求头中中的token
        String token = servletRequest.getHeader("token");
        //判断是否有token -> 是否绕过登录
        if (Objects.isNull(token)) {
            //设置UTF-8编码
            writerErrorResponse(servletResponse,"请先登录");
            return false;
        }
        // 使用jwt验证 token
        //验证token合法性
        try{
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
            if (Objects.isNull(emp)||!emp.getPassword().equals(jsonObject.getString("password"))){
                writerErrorResponse(servletResponse,"Token不合法或已过期");
                return false;
            }
        }catch (Exception e){
            writerErrorResponse(servletResponse,"Token不合法或已过期");
            return false;
        }

        //过滤链对象执行完过滤逻辑之后放行http请求,把request和response重新交给controller(servlet)
      //  chain.doFilter(request, response);
        log.info("过滤完成");
        return true;
    }
    private static void writerErrorResponse(HttpServletResponse servletResponse ,String msg) throws IOException {
        servletResponse.setContentType("application/json;charset=UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        //设置响应状态码401
        //   servletResponse.setStatus(401);
        servletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = servletResponse.getWriter();
        ResultUtil fail = ResultUtil.fail(msg);
        //使用fastjson把对象转成json字符串
        writer.write(JSONObject.toJSONString(fail));
    }
}
